//包含 headers Authorization
function authPost(url, data, callback) {
    var Authorization = getCache("Authorization") ? getCache("Authorization") : "";
    var headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': Authorization,
    };
    api.showProgress({
        title: '加载中...',
        text: '',
        modal: true,
        animationType: 'zoom'
    });
    setTimeout(function() {
        api.hideProgress();
    }, 5000);
    POST(url, data, callback, headers);
}

//包含 headers Authorization
function authPostNoProgress(url, data, callback) {
    var Authorization = getCache("Authorization") ? getCache("Authorization") : "";
    var headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': Authorization,
    };
    POST(url, data, callback, headers);
}

//包含 headers Authorization
function authGet(url, callback) {
    var Authorization = getCache("Authorization") ? getCache("Authorization") : "";
    var headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': Authorization,
    };
    POST(url, headers, callback);
}
//基本post请求
function POST(url, data, callback, headers) {
    var headers = headers ? headers : {
        'Content-Type': 'application/x-www-form-urlencoded'
    };
    var connectionType = api.connectionType;
    if (connectionType == "none") {
        api.toast({
            msg: "当前无网络！",
            duration: 4000,
            location: 'bottom'
        });
        return;
    }

    var closeProgress = false;
    api.ajax({
        url: _Config.baseUrl + url,
        method: 'post',
        headers: headers,
        data: {
            values: data
        }
    }, function(ret, err) {
        if (err) {
            alert("服务器开小差了，请刷新重试");
            return;
        }
        api.hideProgress();
        closeProgress = true;
        if (ret) {
            if (ret.code == 109) {
                removeCache("Authorization");
                removeCache("userinfo");
            }
            callback(ret);
        } else {
            callback(err);
        }
    });
}

//基本 get方法
function GET(url, callback, headers) {
    var headers = headers ? headers : {
        'Content-Type': 'application/x-www-form-urlencoded'
    };
    api.ajax({
        url: _Config.baseUrl + url,
        method: 'get',
        headers: headers
    }, function(ret, err) {
        if (ret) {
            callback(ret);
        } else {
            callback(err);
        }
    });
}

function json_encode(obj) {
    return JSON.stringify(obj)
}

function json_decode(s) {
    var j = JSON.parse(s);
    return j;
}

function time() {
    return Math.floor(new Date().getTime() / 1000);
}

function setCache(key, data) {
    try {
        var data = json_encode(data);
        api.writeFile({
            //path: 'fs://' + key + '.txt',
            path: 'cache://' + key + '.txt',
            data: data
        }, function(ret, err) {
            if (ret.status) {
                //成功
            } else {
                alert('存储失败');
            }
        });
        return "";
    } catch (e) {
        return "";
    }
}

function getCache(key) {
    try {
        //同步返回结果：
        var data = api.readFile({
            sync: true,
            //path: 'fs://' + key + '.txt'
            path: 'cache://' + key + '.txt'
        });
        return json_decode(data);
    } catch (e) {
        return "";
    }
}

function removeCache(key) {
    try {
        var data = '';
        api.writeFile({
            path: 'cache://' + key + '.txt',
            data: data
        }, function(ret, err) {
            if (ret.status) {
                //成功
            } else {
                alert('存储失败');
            }
        });
    } catch (e) {
        return "";
    }

}
//通知刷新用户数据
function refreshDataEvent() {
    api.sendEvent({
        name: 'refreshData'
    });
}

//修改用户本地数据
function changeLocalUserinfo(key, val) {
    var userinfo = getCache("userinfo");
    userinfo[key] = val;
    setCache("userinfo", userinfo);
    refreshDataEvent();
}

function refreshOnlineUserinfo() {
    authPostNoProgress('/api/user/profile', {}, function(res) {
        setCache("userinfo", res.data);
    });
}

//更新用户数据到最新状态
function refreshOnlineData() {
    var jsfun = 'refreshData();';
    api.execScript({
        name: 'main',
        frameName: 'userinfo',
        script: jsfun
    });
}

function R(page) {
    return 'widget://html/' + page + '.html';
}

function Rc(filepath) {
    return 'widget://common/' + filepath + '.js';
}

function toMain(pageid) {
    var pageid = pageid ? pageid : 0;
    api.openWin({
        slidBackEnabled: false,
        name: 'main',
        url: R('common/main'),
        animation: {
            type: "push", //动画类型（详见动画类型常量）
            subType: "from_left", //动画子类型（详见动画子类型常量）
            duration: 300 //动画过渡时间，默认300毫秒
        },
        pageParam: {
            pageId: pageid
        }
    });
}

function toWin(pageName, pageParam) {
    if (!checkLogin()) {
        return;
    }
    var pageParam = pageParam ? pageParam : {};
    api.openWin({
        onload: true,
        slidBackEnabled: false,
        name: pageName,
        url: R(pageName),
        animation: {
            type: "push", //动画类型（详见动画类型常量）
            subType: "from_right", //动画子类型（详见动画子类型常量）
            duration: 300 //动画过渡时间，默认300毫秒
        },
        pageParam: pageParam
    });
}
function toWinLeft(pageName, pageParam) {
    if (!checkLogin()) {
        return;
    }
    var pageParam = pageParam ? pageParam : {};
    api.openWin({
        onload: true,
        slidBackEnabled: false,
        name: pageName,
        url: R(pageName),
        animation: {
            type: "push", //动画类型（详见动画类型常量）
            subType: "from_left", //动画子类型（详见动画子类型常量）
            duration: 300 //动画过渡时间，默认300毫秒
        },
        pageParam: pageParam
    });
}

function toWinNoLogin(pageName, pageParam) {
    var pageParam = pageParam ? pageParam : {};
    api.openWin({
        slidBackEnabled: false,
        name: pageName,
        url: R(pageName),
        animation: {
            type: "push", //动画类型（详见动画类型常量）
            subType: "from_right", //动画子类型（详见动画子类型常量）
            duration: 300 //动画过渡时间，默认300毫秒
        },
        pageParam: pageParam
    });
}

function p(o) {
    console.log(json_encode(o));
}

function tologin() {
    api.openWin({
        reload: true,
        slidBackEnabled: false,
        name: 'login',
        url: R('login_and_register'),
        animation: {
            type: "push", //动画类型（详见动画类型常量）
            subType: "from_right", //动画子类型（详见动画子类型常量）
            duration: 300 //动画过渡时间，默认300毫秒
        }
    });
}

function tologinLeft() {
    api.openWin({
        reload: true,
        slidBackEnabled: false,
        name: 'login',
        url: R('login_and_register'),
        animation: {
            type: "push", //动画类型（详见动画类型常量）
            subType: "from_left", //动画子类型（详见动画子类型常量）
            duration: 300 //动画过渡时间，默认300毫秒
        }
    });
}

function logout() {
    removeCache("Authorization");
    removeCache("userinfo");
    refreshOnlineData();
    api.closeWin({
        name: 'main'
    });

    api.openWin({
        name: 'login',
        url: R('login_and_register')
    });
}

function checkLogin() {
    if (!getCache('Authorization')) {
        tologin();
        return false;
    } else {
        return true;
    }
}

//计算版本号大小,转化大小
function toNum(a) {
    var a = a.toString();
    var c = a.split('.');
    var num_place = ["", "0", "00", "000", "0000"],
        r = num_place.reverse();
    for (var i = 0; i < c.length; i++) {
        var len = c[i].length;
        c[i] = r[len] + c[i];
    }
    var res = c.join('');
    return res;
}

function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {
        type: mime
    });
}

function upFile(ret, callback) {
    if (!ret) {
        return;
    }
    POST('/api/up/getToken', {}, function(response) {
        var putExtra = {
            fname: "",
            params: {},
            mimeType: ["image/png", "image/jpeg", "image/jpg"]
        };
        var config = {
            useCdnDomain: true,
            region: qiniu.region.z0
        };
        var observer = {
            next: function(res) {
                //alert(JSON.stringify(res));  上传图片进度    进度条
            },
            error: function(err) {
                callback(false);
            },
            complete: function(res) {
                var images = 'http://imgs.wbwan.vip/' + res.key;
                callback(images);
            }
        };
        if (response.uptoken) {
            var suffix = ret.data.split(".").pop();
            var filename = Date.parse(new Date()) + '.' + suffix;
            var observable = qiniu.upload(dataURLtoBlob(ret.base64Data), filename, response.uptoken, putExtra, config);
            subscription = observable.subscribe(observer);
        } else {
            callback(false);
        }
    });
}

function fomatHtml(id, width) {
    var width = width ? width : false;
    var taskExplain = $api.domAll(document.getElementById(id), "img");
    for (var i in taskExplain) {
        taskExplain[i].onload = function() {
            // this.onclick = function() {
            //     $api.attr($api.byId('showimg'), 'src', $api.attr(this, 'src'));
            //     $api.css($api.byId('mask'), 'display:block;');
            // }
            if (width) {
                $api.attr(this, 'width', width + 'px');
            } else {
                if ($api.offset(this).w > (api.winWidth - 50)) {
                    var w = api.winWidth - 150;
                    $api.removeAttr(this, 'width');
                    $api.removeAttr(this, 'height');
                    $api.attr(this, 'width', '90%');
                }
            }

            $(this).click(function() {
                var imageBrowser = api.require('imageBrowser');
                imageBrowser.openImages({
                    imageUrls: [
                        $(this).attr('src')
                    ]
                });
            });
        }
    }
    $('#'+id).find('a').attr('href','jacascript::void(0)');
    $('#'+id).find('a').click(function(){
          var currentUrl = $(this).text();
          clipBoardLive(currentUrl);
     });
}

function clipBoardLive(value){
  var clipBoard = api.require('clipBoard');
  clipBoard.set({
      value:value
  }, function(ret, err) {
      if (ret) {
          api.toast({
              msg: "链接复制成功",
              duration: 2000,
              location: 'bottom'
          });
      } else {
          api.toast({
              msg: "复制到剪切板失败",
              duration: 2000,
              location: 'bottom'
          });
      }
  });
}

function noData(path){
  var path = path ? path : "../";
  return '<div id="no_data_id">'+
         '<div class="img" style="width:100%;height:auto;text-align: center;padding-top:0.4rem;color:#A1A0A0;">'+
         '<img src="'+path+'image/nodata.png" alt="" style="width: 160px;height: 106px;">'+
         '<p style="padding-top: 0.1rem;">暂无内容</p>'+
         '</div>'+
         '</div>';
}

function homeNoData(){
    var str = ['<div id="homenodata-page">',
               '<div class="img" style="width:100%;height:auto;text-align: center;padding-top:0.4rem;color:#A1A0A0;">',
               '<img src="../image/homeNodata.png" alt="" style="width: 160px;height: 106px;">',
               '<p style="padding-top: 0.1rem;">该类型的任务暂无数据，请做一做其他类型的任务吧</p>',
               '<p>我们会尽快上新的任务！</p>',
               '</div>',
               '</div>'].join("");
    return str
}



function toTheEnd(){
   return '<div id="to_the_end_id" class="no-search" style="display: box;display: -webkit-box;box-orient:horizontal;-webkit-box-orient: horizontal;box-align:center;-webkit-box-align:center;box-pack: center;-webkit-box-pack: center;  height: 0.62rem;color: #878787;">'+
          '<div class="line" style="width: 0.26rem;height: 0.01rem;background: #d9d9d9;"></div>'+
          '<div class="tip" style="padding:0 0.1rem;">已经到底啦</div>'+
          '<div class="line" style="width: 0.26rem;height: 0.01rem;background: #d9d9d9;"></div>'+
      '</div>';
}

function fomatList(currentpage,id,content,callback){
  $('#no_data_id').remove();
  $('#to_the_end_id').remove();
  if(content==''){
    if(currentpage==1){
      $(id).html(callback);
    }else{
      $(id).append(toTheEnd());
    }
  }
}

function iosCheckLogin() {
    if (!getCache('Authorization')) {
        api.openWin({
            slidBackEnabled: false,
            name: 'ioslogin',
            url: R('iosmode/login'),
            animation: {
                type: "push", //动画类型（详见动画类型常量）
                subType: "from_left", //动画子类型（详见动画子类型常量）
                duration: 300 //动画过渡时间，默认300毫秒
            }
        });
        return false;
    } else {
        return true;
    }
}



function iosToWin(pageName, pageParam) {
    if (!iosCheckLogin()) {
        return;
    }
    var pageParam = pageParam ? pageParam : {};
    api.openWin({
        onload: true,
        slidBackEnabled: false,
        name: pageName,
        url: R(pageName),
        animation: {
            type: "push", //动画类型（详见动画类型常量）
            subType: "from_right", //动画子类型（详见动画子类型常量）
            duration: 300 //动画过渡时间，默认300毫秒
        },
        pageParam: pageParam
    });
}

/**
 * 时间戳转化为年 月 日 时 分 秒
 * number: 传入时间戳
 * format：返回格式，支持自定义，但参数必须与formateArr里保持一致
*/
function timestampToTime(timestamp) {
        var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var Y = date.getFullYear() + '-';
        var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        var D = date.getDate() + ' ';
        var h = date.getHours() + ':';
        var m = date.getMinutes() + ':';
        var s = date.getSeconds();
        // return Y+M+D+h+m+s;
        return Y+M+D;
    }

    function phonehide(tel) {
          tel = "" + tel;
          var ary = tel.split("");
          ary.splice(3,4,"****");
          var tel_hide=ary.join("");
          return tel_hide
    }
